<template>
  <!-- label-position 对齐方式 -->
  <el-form
    label-position="left"
    label-width="10px"
    :model="registerData"
    :rules="rules"
    ref="formData"
  >
    <el-form-item prop="email">
      <el-input
        v-model="registerData.email"
        prefix-icon="el-icon-message"
      ></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="registerData.password"
        prefix-icon="el-icon-lock"
        show-password
      ></el-input>
    </el-form-item>
    <el-form-item prop="captcha">
      <el-row>
        <el-col :span="16">
          <el-input
            v-model="registerData.captcha"
            prefix-icon="el-icon-circle-check"
          ></el-input>
        </el-col>
        <el-col :span="8">
          <el-button
            @click="sendEmailCode(registerData.email)"
            style="margin-left: 20px"
            >{{ time === 0 ? "发送验证码" : `${time}秒后发送` }}</el-button
          >
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" style="width: 95%"
        >注册</el-button
      >
    </el-form-item>
    <router-link to="/login" class="register">已有账号？立即登录吧</router-link>
    <el-form-item prop="checked">
      <el-checkbox v-model="registerData.checked">
        <p>
          阅读并接受
          <a href="javascript:;"> 《小兔仙用户协议》 </a>
          及
          <a href="javascript:;"> 《小兔仙隐私权保护声明》 </a>
        </p>
      </el-checkbox>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { Component, Vue, Ref, Watch } from "vue-property-decorator";
import { registerUser, emailCode } from "@/api/index";
// import { useIntervalFn } from "@vueuse/shared";
import { ElForm } from "element-ui/types/form";

// BUG
// const Fn = (time:number) => {
//   const {pause,resume} = useIntervalFn(
//     () => {
//       // console.log(time);
//       time--
//       if(time <= 0){
//         pause()
//       }
//     },
//     1000,
//     { immediate: false }
//   );
//   console.log(time);
//   return {pause,resume,time}
// }
@Component({
  name: "EmailForm",
  components: {},
})
export default class EmailForm extends Vue {
  registerData = {
    email: "",
    password: "",
    captcha: "",
    type: "email", // 默认类型是 email
    checked: true,
  };
  private validateEmail = (rule: any, value: string, callback: any) => {
    const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    if (!value) {
      callback(new Error("请输入邮箱"));
    } else if (!reg.test(value)) {
      callback(new Error("邮箱格式不正确"));
    } else {
      callback();
    }
  };
  private validatePwd = (rule: any, value: string, callback: any) => {
    const reg =
      /^(?:(?=.*[0-9].*)(?=.*[A-Za-z].*)(?=.*[,\.#%'\+\*\-:;^_`].*))[,\.#%'\+\*\-:;^_`0-9A-Za-z]{8,}$/;
    if (!value) {
      callback(new Error("请输入密码"));
    } else if (value.length < 8) {
      callback(new Error("密码至少是8位"));
    } else if (!reg.test(value)) {
      callback(new Error("密码必须是数字字母符号组合"));
    } else {
      callback();
    }
  };
  private validateCapt = (rule: any, value: string, callback: any) => {
    const reg = /^[A-Za-z0-9]{4}$/;
    if (!value) {
      callback(new Error("请输入验证码"));
    } else if (value.length < 4) {
      callback(new Error("验证码至少是4位"));
    } else if (!reg.test(value)) {
      callback(new Error("验证码必须是数字或字母组成"));
    } else {
      callback();
    }
  };
  private validateChecked = (rule: any, value: string, callback: any) => {
    if (!value) {
      callback(new Error("请阅读并同意用户协议"));
    } else {
      callback();
    }
  };
  // 校验规则
  rules = {
    email: [{ validator: this.validateEmail, trigger: "blur" }],
    password: [{ validator: this.validatePwd, trigger: "blur" }],
    captcha: [{ validator: this.validateCapt, trigger: "blur" }],
    checked: [{ validator: this.validateChecked, trigger: "change" }],
  };
  // 点击更新验证码
  @Ref() readonly imageCaptcha!: HTMLImageElement; // imageCaptcha! !一定有
  private updateCaptcha() {
    // 强制转成 any 有点不符合 TS 的思想
    //   (this.$refs.imageCaptcha as any).src = `http://127.0.0.1:7001/api/imagecode?r=${Math.random()}`
    this.imageCaptcha.src = `http://127.0.0.1:7001/api/imagecode?r=${Math.random()}`;
  }
  
  // @Watch(path)

  private time = 0
  private timeId:any
  // vueUse的定时器
  // 发送验证码 resume
  @Ref() readonly formData!: ElForm;
  private sendEmailCode(email: string) {
    if(this.time !== 0) return
    clearInterval(this.timeId)
    this.time = 60
    // 校验邮箱格式
    this.formData.validateField("email", (errorMessage: string) => {
      if (!errorMessage) {
        // 通过倒计时没有结束直接退出
        // if (this.time !== 0) return;
        // 倒计时重置
        // this.time = 60;
        // 调用倒计时
        // Fn(this.time).resume()
        this.timeId = window.setInterval(() => {
         this.time--
         if(this.time <= 0){
           clearInterval(this.timeId)
         }
        },1000)
        // 在组件被销毁之前, 也销毁这个日期选择器
        this.$once('hook:beforeDestroy',()=>{
          window.clearInterval(this.timeId)
        })
        try {
          emailCode(email)
            .then((response: any) => {
              if (response.status === 200) {
                (this as any).$message.success("验证码发送成功");
              } else {
                (this as any).$message.error(response.data.msg);
              }
            })
            .catch((e) => {
              (this as any).$message.error(e.response.data.msg);
            });
        } catch (e) {
          (this as any).$message.error(e.message);
        }
      }
    });
  }
  // 注册
  private onSubmit() {
    this.formData.validate((valid: boolean) => {
      if (valid) {
        // 校验通过, 发送请求
        registerUser(this.registerData)
          .then((data: any) => {
            console.log(data);
            if (data.code === 200) {
              // 注册成功跳转登录界面
              (this as any).$message.success("注册成功");
              this.$router.push("/login");
              this.updateCaptcha()
            } else {
              (this as any).$message.error(data.msg);
            }
          })
          .catch((e) => {
            (this as any).$message.error(e.message);
          });
      } else {
        (this as any).$message.error("数据格式不对");
      }
    });
  }
  // 重置表单
  public resetForm() {
    this.formData.resetFields();
  }
}
</script>

<style lang="scss" scoped>
a {
  text-decoration: none;
}
.el-col {
  height: 40px;
}
.el-form {
  padding-right: 20px;
  box-sizing: border-box;
}
.register {
  display: block;
  font-size: 15px;
  color: #407ffe;
  text-align: center;
  // margin-bottom: 10px;
  text-decoration: none;
}
</style>
